package com.hz.house.service.detail;

import com.hz.house.bean.entity.BuildingOpenLotteryBind;
import com.hz.house.bean.entity.LotteryBind;
import com.hz.house.bean.entity.MyLottery;
import com.hz.house.bean.entity.OpenResult;
import com.hz.house.common.ResultBean;
import com.hz.house.common.ResultUtil;
import com.hz.house.dao.KaiPanResultSearchMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.regex.Pattern;

/**
 * 开盘、摇号结果相关
 */
@Service
public class KaiPanResultSearchImpl implements KaiPanResultSearchService {

	@Autowired
	private KaiPanResultSearchMapper searchMapper;

	/**
	 * 查询摇号结果
	 *
	 * @param buildingId
	 * @return
	 */
	@Override
	public ResultBean queryLotteryResult(Integer page, Integer buildingId, String orderNum, String yhType,
			String searchWord) {
		if (page == null || page < 0) {
			page = 0;
		} else {
			page = (page - 1) * 10;
		}
		if (buildingId == null)
			return ResultUtil.fail("该楼盘不存在");
		if (StringUtils.isEmpty(orderNum))
			return ResultUtil.fail("该楼盘尚未取证");
		List<OpenResult> openResult = searchMapper.queryLotteryResult(page, orderNum, yhType, searchWord);
		if (openResult != null && openResult.size() > 0) {
			for (OpenResult re : openResult) {
				String names = re.getNames();
				if (!StringUtils.isEmpty(names)) {
					re.setNamesArr(names.split("\\+"));
				}
				String ids = re.getIdNums();
				if (!StringUtils.isEmpty(ids)) {
					re.setIdsArr(ids.split("\\+"));
				}
				re.setNames(null);
				re.setIdNums(null);
			}
		}
		String bname = searchMapper.findBuildingName(buildingId);
		Integer total = searchMapper.countYh(orderNum, yhType, searchWord);
		if (StringUtils.isEmpty(bname)) {
			return ResultUtil.fail("该楼盘不存在");
		}
		Map<String, Object> m = new HashMap<>();
		m.put("bname", bname);
		m.put("openResult", openResult);
		m.put("total", total);
		return ResultUtil.ok(m);
	}

	/**
	 * 查询复核结果
	 * 
	 * @param buildingId
	 * @return
	 */
	@Override
	public ResultBean queryVerifyResult(Integer page, Integer buildingId, String orderNum, String fhType,
			String searchWord) {
		if (page == null || page < 0) {
			page = 0;
		} else {
			page = (page - 1) * 10;
		}
		if (StringUtils.isEmpty(orderNum))
			return ResultUtil.fail("该楼盘尚未取证");
		List<OpenResult> openResult = searchMapper.queryVerifyResult(page, orderNum, searchWord, fhType);
		if (openResult != null && openResult.size() > 0) {
			for (OpenResult re : openResult) {
				String ids = re.getIdNums();
				if (!StringUtils.isEmpty(ids)) {
					re.setIdsArr(ids.split("\\+"));
				}
				String names = re.getNames();
				if (!StringUtils.isEmpty(names)) {
					re.setNamesArr(names.split("\\+"));
				}
				re.setNames(null);
				re.setIdNums(null);
			}
		}
		String bname = searchMapper.findBuildingName(buildingId);
		Integer total = searchMapper.countFh(orderNum, searchWord, fhType);
		if (StringUtils.isEmpty(bname))
			return ResultUtil.fail("该楼盘不存在");
		Map<String, Object> m = new HashMap<>();
		m.put("bname", bname);
		m.put("total", total);
		m.put("openResult", openResult);
		return ResultUtil.ok(m);
	}

	/**
	 * 查询我的摇号
	 * 
	 * @param orderNum
	 * @param yhNum
	 * @return
	 */
	@Override
	public ResultBean findMyLottery(String orderNum, String yhNum, Integer openId, String regNum) {
		if (StringUtils.isEmpty(yhNum) && StringUtils.isEmpty(regNum))
			return ResultUtil.fail("请填写公证摇号编号或购房登记号至少一个完整信息");
		if (StringUtils.isEmpty(orderNum))
			return ResultUtil.fail("该楼盘目前不在摇号期内");
		if (openId == null)
			return ResultUtil.fail("该楼盘目前不在摇号期内");
		// 查询选房序号
		List<OpenResult> list = searchMapper.findMyLottery(orderNum, yhNum, regNum);
		// 查询房源信息
		MyLottery lottery = searchMapper.findFyInfo(openId);
		if (lottery != null) {
			lottery.setTotalHouseNum(lottery.getGxHouseNum() + lottery.getPgHouseNum() + lottery.getPtHouseNum());
			lottery.setResultList(list);
			// 处理是否中签
			lottery.setDescription(getDesciption(list, lottery));
		} else if (list != null && list.size() > 0) {
			lottery = new MyLottery();
			lottery.setResultList(list);
		}
		return ResultUtil.ok(lottery);
	}

	private String getDesciption(List<OpenResult> list, MyLottery lottery) {
		if (list.size() == 0)
			return "未查询到该摇号编码信息";
		if (list.size() == 1) {
			OpenResult x = list.get(0);
			if (x.getYhType().equals("necessity"))
				return getDescx(doGetDescription(x.getSort(), lottery.getGxHouseNum()));
			else if (x.getYhType().equals("shanty"))
				return getDescx(doGetDescription(x.getSort(), lottery.getPgHouseNum()));
			else
				return getDescx(doGetDescription(x.getSort(), lottery.getPtHouseNum()));
		} else {
			// 如果第一个没中签，以第二个为准
			OpenResult x = list.get(0);
			if (x.getYhType().equals("necessity")) {
				int e = doGetDescription(x.getSort(), lottery.getGxHouseNum());
				if (e == 1)
					return getDescx(e);
			} else if (x.getYhType().equals("shanty")) {
				int e = doGetDescription(x.getSort(), lottery.getPgHouseNum());
				if (e == 1)
					return getDescx(e);
			} else {
				int e = doGetDescription(x.getSort(), lottery.getPtHouseNum());
				if (e == 1)
					return getDescx(e);
			}
			// 判断普通号
			OpenResult y = list.get(1);
			if (y.getYhType().equals("necessity"))
				return getDescx(doGetDescription(y.getSort(), lottery.getGxHouseNum()));
			else if (y.getYhType().equals("shanty"))
				return getDescx(doGetDescription(y.getSort(), lottery.getPgHouseNum()));
			else
				return getDescx(doGetDescription(y.getSort(), lottery.getPtHouseNum()));
		}
	}

	private String getDescx(int x) {
		switch (x) {
		case 0:
			return "未查询到该编码摇号信息!";
		case 1:
			return "恭喜您中签，做好准备去选房吧!";
		case 2:
			return "您还有机会，请等侯售楼部通知!";
		case 3:
			return "很遗憾您没中签，请注意售楼部消息!";
		default:
			return "未查询到该编码摇号信息!";
		}
	}

	private int doGetDescription(Integer sort, Integer houseSource) {
		if (houseSource == null || houseSource == 0)
			return 0;
		if (sort == null || sort == 0)
			return 0;
		if (sort <= houseSource)
			return 1;
		if (sort > houseSource && sort <= (houseSource * 1.2f))
			return 2;
		else
			return 3;
	}

	/**
	 * 查询楼盘及开盘信息
	 * 
	 * @param buildingName
	 * @return
	 */
	public ResultBean findBuilding(String buildingName) {
		if (StringUtils.isEmpty(buildingName))
			return ResultUtil.fail("请输入楼盘名");
		// 校验楼盘名
		String regEx = "[ _`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]|\n|\r|\t";
		Pattern p = Pattern.compile(regEx);
		boolean flag = p.matcher(buildingName).find();
		if (flag)
			return ResultUtil.fail("楼盘名称不能包含特殊字符");
		List<LotteryBind> list = searchMapper.findBuilding(buildingName);
		String str;
		if (list != null && list.size() > 0) {
			for (LotteryBind bind : list) {
				if (!StringUtils.isEmpty(bind.getOrderNum())) {
					str = bind.getBuildingName() + "[" + bind.getOrderNum() + "]";
					bind.setBuildingName(str);
				}
			}
		}
		return ResultUtil.ok(list);
	}

	/**
	 * 新增我的绑定
	 * 
	 * @param bind
	 * @return
	 */
	@Override
	public ResultBean addMyBind(LotteryBind bind) {
		if (bind.getBuildingId() == null)
			return ResultUtil.fail("当前楼盘不存在");
		if (StringUtils.isEmpty(bind.getOpenId()))
			return ResultUtil.fail("该楼盘目前不在摇号期内");
		if (StringUtils.isEmpty(bind.getOrderNum()))
			return ResultUtil.fail("该楼盘尚未取证");
		if (StringUtils.isEmpty(bind.getRegNum()) && StringUtils.isEmpty(bind.getYhNum()))
			return ResultUtil.fail("请输入摇号编号或者购房登记号的至少一个完整信息");
		if (StringUtils.isEmpty(bind.getBindName()))
			return ResultUtil.fail("请输入绑定的姓名");
		bind.setCreateDate(new Date());
		searchMapper.addMyBind(bind);
		return ResultUtil.ok();
	}

	/**
	 * 查询用户所有绑定
	 * 
	 * @param currentUserId
	 * @return
	 */
	@Override
	public ResultBean findUserBind(Integer currentUserId) {
		List<BuildingOpenLotteryBind> userBind = searchMapper.findUserBind(currentUserId);
		return ResultUtil.ok(userBind);
	}
}
